<template>
    <div v-loading="loading" element-loading-text="登录中..." element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.6)" class="login-container">

        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on"
            label-position="left">
            <!-- 头像区域 -->
            <div v-if="TxStatus" class="avatar-box">
                <img src="../../../public/images/Layout/touxiang.jpg" alt="">
            </div>

            <div class="title-container">
                <h3 class="title">后台管理系统 登录</h3>
            </div>

            <el-form-item prop="username">

                <el-input ref="username" v-model="loginForm.username" placeholder="请输入5-8位字母、数字、下划线用户名" name="username"
                    type="text" tabindex="1" auto-complete="on" />
            </el-form-item>

            <el-form-item prop="password">
                <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
                    placeholder="请输入4到16位（字母，数字，下划线，减号）的密码" name="password" tabindex="2" auto-complete="on"
                    @keyup.enter.native="handleLogin" show-password/>
            </el-form-item>

            <div class="goRegister"><span @click="register">没有账号? 去注册</span></div>

            <div>
                <el-button type="primary" style="width:100%;margin-bottom:20px;"
                    @click.native.prevent="handleLogin">登录</el-button>
            </div>


        </el-form>
    </div>
</template>
 
<script>
// 引入去除空格工具
import { validUsername } from '@/utils/validate'
// 引入userLogin api
import userLogin from '@/api/login'
import { getAllUser } from '@/api/login'

export default {
    name: 'Login',
    data() {
        const validateUsername = (rule, value, callback) => {
            if (value.length < 5 || value.length > 10) {
                callback(new Error('请输入5-8位字母、数字、下划线用户名'))
            } else {
                callback()
            }
        }
        const validatePassword = (rule, value, callback) => {
            if (value.length < 6 || value.length > 16) {
                callback(new Error('请输入4到16位（字母，数字，下划线，减号）的密码'))
            } else {
                callback()
            }
        }
        return {
            // 头像状态
            TxStatus: true,
            loginForm: {
                username: '',
                password: ''
            },
            // 登录规则
            loginRules: {
                username: [
                    // { required: true, message: '请输入用户名', trigger: 'blur' },
                    // { pattern: /^\w{5,10}$/, message: '用户名不符合要求', trigger: 'blur' },
                    { required: true, trigger: 'blur', validator: validateUsername }
                ],
                password: [{ required: true, trigger: 'blur', validator: validatePassword }]
            },
            loading: false,
            passwordType: 'password',
            redirect: undefined
        }
    },
    watch: {
        $route: {
            handler: function (route) {
                this.redirect = route.query && route.query.redirect
            },
            immediate: true
        }
    },
    methods: {
        // 判断数组对象中是否有某个属性值
        findElem(arrayToSearch, attr, val) {
            for (var i = 0; i < arrayToSearch.length; i++) {
                if (arrayToSearch[i][attr] == val) {
                    return i;
                }
            }
            return -1;
        },

        async handleLogin() {

            let flag = false
            let _num = -1
            const reg_name = /^\w{5,10}$/
            //密码正则，4到16位（字母，数字，下划线，减号）
            const reg_pass = /^[a-zA-Z0-9_-]{4,16}$/

            // 判断 输入框内容是否通过验证
            if (reg_name.test(this.$refs.username.value.trim()) && reg_pass.test(this.$refs.password.value.trim())) {
                let _userArr = await getAllUser()
                _userArr.data.filter(item => {
                    // 判断账户是否存在 如果有就返回
                    _num = this.findElem(_userArr.data, 'account', this.$refs.username.value.trim())
                    // 判断账户密码是否正确
                    if (item.account == this.$refs.username.value.trim() && item.password == this.$refs.password.value.trim()) {
                        flag = true
                    }
                })
                // console.log(_num);
                if (_num == -1) {
                    this.$message({
                        message: '您的账号未注册！请先注册再登录',
                        type: 'error'
                    });
                } else {
                    if (flag) {
                        this.$message({
                            message: '登录成功',
                            type: 'success'
                        });

                        this.$store.dispatch('isLogin')
                        this.$store.dispatch('changeName', this.$refs.username.value.trim())

                        localStorage.setItem('isLogin', true)
                        localStorage.setItem('userName', this.$refs.username.value.trim())

                        // 设置登录过期时间
                        let _endTime = 1000 * 60 * 60 * 24 + Date.now()
                        localStorage.setItem('endTime', _endTime)
                        this.$store.dispatch('setEndTime', _endTime)

                        this.$router.push(this.$route.params.fromUrl || '/home')
                    } else {
                        this.$message({
                            message: '您输入的密码不正确',
                            type: 'error'
                        });
                    }
                }

            }



        },
        // 注册业务
        register() {
            this.$router.push('/register')
        }
    }
}
</script>
 
<style lang="scss">
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
        color: $cursor;
    }
}

.login-container {
    height: 100vh;

    .el-input {
        display: inline-block;
        height: 47px;
        width: 100%;
        border-radius: 5px;

        input {
            background: transparent;
            border: 0px;
            // -webkit-appearance: none;
            border-radius: 0px;
            padding: 12px 5px 12px 15px;
            color: $light_gray;
            height: 47px;
            caret-color: $cursor;

            &:-webkit-autofill {
                box-shadow: 0 0 0px 1000px $bg inset !important;
                -webkit-text-fill-color: $cursor !important;
            }
        }
    }

    .el-form-item {
        border: 1px solid rgba(255, 255, 255, 0.1);
        background: rgba(0, 0, 0, 0.1);
        border-radius: 5px;
        color: #454545;
    }
}
</style>
 
<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
    min-height: 100%;
    width: 100%;
    overflow: hidden;
    background: url('./../../../public/images/Login/bg0.jpeg');
    background-size: 100% 100%;

    // 头像
    .avatar-box {
        margin: 0 auto;
        width: 120px;
        height: 120px;
        border-radius: 50%;
        border: 1px solid #409eff;
        box-shadow: 0 0 10px #409eff;
        position: relative;
        bottom: 20px;

        img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
        }
    }

    .login-form {
        position: relative;
        width: 520px;
        max-width: 100%;
        padding: 160px 35px 0;
        margin: 0 auto;
        overflow: hidden;

    }

    .tips {
        font-size: 18px;
        text-align: center;
        color: #000;
        margin-bottom: 10px;
    }

    .svg-container {
        padding: 6px 5px 6px 15px;
        color: $dark_gray;
        vertical-align: middle;
        width: 30px;
        display: inline-block;
    }

    .title-container {
        position: relative;

        .title {
            font-size: 30px;
            color: $light_gray;
            margin: 0px auto 40px auto;
            text-align: center;
            font-weight: 500;
        }
    }

    .show-pwd {
        position: absolute;
        right: 10px;
        top: 7px;
        font-size: 16px;
        color: $dark_gray;
        cursor: pointer;
        user-select: none;
    }
}

// 没有账号 去注册
.goRegister {
    display: flex;
    justify-content: right;
    padding: 10px 0;
    color: #f50;

    span {
        cursor: pointer;
    }

}

.goRegister span:hover {
    text-decoration: underline;
}
</style>